// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package os

import (
	"runtime"
	"syscall"
	"time"
)

// A Signal represents an operating system signal.
// Since HelenOS does not support UNIX-like signals, this is not very useful here.
type Signal interface {
	String() string
	Signal() // to distinguish from other Stringers
}

type killSignal int
func (s killSignal) Signal() {}
func (s killSignal) String() string {
	return "Kill signal"
}

type intSignal int
func (s intSignal) Signal() {}
func (s intSignal) String() string {
	return "Int signal"
}

var (
	Interrupt Signal = intSignal(0)
	Kill      Signal = killSignal(0)
)


// Process stores the information about a process created by StartProcess.
type Process struct {
	Pid    int
	done   bool // process has been successfully waited on
}

type ProcAttr struct {
	Dir string
	// HelenOS does not have envvars yet. This does nothing.
	Env []string
	// This only makes sense for the first three fd's (stdin, stdout, stderr).
	Files []*File
	// Operating system-specific process creation attributes.
	// On HelenOS, this structure is empty.
	Sys *syscall.SysProcAttr
}

func newProcess(pid int) *Process {
	p := &Process{Pid: pid}
	runtime.SetFinalizer(p, (*Process).Release)
	return p
}

func FindProcess(pid int) (p *Process, err error) {
	return newProcess(pid), nil
}

func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error) {
	if attr.Dir != "" {
		defer syscall.Chdir(syscall.Getcwd())
		if err := syscall.Chdir(attr.Dir); err != nil {
			return nil, err
		}
	}
	
	// TODO: attr.Env
	
	files := make([]*int, len(attr.Files))
	for i, file := range attr.Files {
		files[i] = new(int)
		*(files[i]) = int(file.Fd())
	}

	pid, err := syscall.TaskSpawn(name, argv, files)
	if err != nil {
		return nil, &PathError{"TaskSpawn", name, err}
	}
	return newProcess(pid), nil
}

func (p *Process) Release() error {
	p.done = true
	return nil
}

func (p *Process) Kill() error {
	if p.done {
		return ErrInvalid
	}

	return syscall.TaskKill(p.Pid)
}

func (p *Process) Wait() (*ProcessState, error) {
	if p.done {
		return nil, ErrInvalid
	}

	estatus, retval, err := syscall.TaskWait(p.Pid)
	if err != nil {
		return nil, err
	}
	
	p.done = true
	return &ProcessState{p.Pid, exitStatus{estatus, retval}}, nil
}

func (p *Process) Signal(sig Signal) error {
	if p.done {
		return ErrInvalid
	}

	switch sig {
	case Interrupt:
		return hosError
	case Kill:
		return p.Kill()
	}
	return ErrInvalid
}

type ProcessState struct {
	pid int
	exit exitStatus
}

type exitStatus struct {
	status int
	retval int
}

func (p *ProcessState) UserTime() time.Duration {
	return ^time.Duration(0)
}

func (p *ProcessState) SystemTime() time.Duration {
	return ^time.Duration(0)
}

func (p *ProcessState) Exited() bool {
	return true
}

func (p *ProcessState) Pid() int {
	return p.pid
}

func (p *ProcessState) Success() bool {
	return p.exit.status == syscall.TASK_EXIT_NORMAL && p.exit.retval == 0
}

func (p *ProcessState) Sys() interface{} {
	return p.exit
}

func (p *ProcessState) SysUsage() interface{} {
	return nil
}

func (p *ProcessState) String() string {
	if p == nil {
		return "<nil>"
	}
	s := "exited "
	if p.exit.status == syscall.TASK_EXIT_NORMAL {
		s = s + "normally with return value "
		s = s + itoa(p.exit.retval)
	} else {
		s = s + "unexpectedly"
	}
	return s
}

